<template>
  <div class="login">
    <h2 class="title">登录</h2>
    <el-form
      ref="form"
      :model="form"
      label-width="80px"
      :rules="rules"
      class="form"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="form.username" prefix-icon="el-icon-phone">
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          prefix-icon="el-icon-eleme"
          suffix-icon="el-icon-view"
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { userLoginApi } from "../apis/user.js";
import { setToken, setID } from "../utils/tokenData";
export default {
  data() {
    return {
      form: {
        username: "13488888888",
        password: "555",
      },
      rules: {
        name: [
          { required: true, message: "请输入正确的账号", trigger: "blur" },
          {
            pattern: /^1\d{10}$|^\d{5,6}$/,
            message: "请输入11位手机号",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入正确的密码", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async onSubmit() {
      this.$refs.form.validate(async (valid) => {
        console.log(valid);
        if (valid) {
          const res = await userLoginApi(this.form);
          if (res.data.message == "登录成功") {
            // console.log('登录接口',res);
            //保存token 和 id
            setToken(res.data.data.token);
            setID(res.data.data.user.id);
            this.$message.success("恭喜你，登录成功");
            this.$router.push({
              path:'/home'
            })
          } else {
            this.$message.error("错误！");
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  background-color: #f2f2f2;
  // 1vw    视口宽度(viewport width)的 1%
  // 1vh    视口高度(viewport height)的 1%
  height: 100vh;
  display: flex;
  align-items: center;
  flex-direction: column;
  padding-top: 10vh;
  box-sizing: border-box;
  .title {
    font-size: 30px;
    margin: 20px 0;
  }
  .form {
    font-size: 20px;
    background-color: #fff;
    width: 400px;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  }
}
</style>